﻿using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;
/// <summary>
/// 基本json 通信的基本http请求客户端基类，如果有新的目标服务需要添加http请求，只需要创建一个类，继承此类即可。
/// </summary>
public abstract class BaseJsonHttpClient<T> : Singleton<T> where T : class
{

    private GameHttpClient gameHttpClient;

    public BaseJsonHttpClient()
    {
        Init();
    }
    private void Init()
    {
        string targetUrl = getTargetUrl();
        gameHttpClient = new GameHttpClient(targetUrl);
    }

    protected abstract string getTargetUrl();
    public IEnumerator SendPostRequest(string path, object param, GameCenterResponse response, OnHttpError onHttpError)
    {
        return SendPostRequest(path, param, null, response, onHttpError);
    }

    public IEnumerator SendPostRequest(string path, object param, Dictionary<string, string> header, GameCenterResponse response, OnHttpError onHttpError)
    {

        return gameHttpClient.SendHttpPost(path, param, header, (result) =>
         {
             try
             {
                 JObject codeObj = JObject.Parse(result);

                 JToken codeToken = codeObj.GetValue("code");

                 int code = codeToken.Value<int>();
                 if (code == 0)
                 {
                     JToken token = codeObj.GetValue("data");
                     response(token);
                 }
                 else
                 {
                     JToken errorToken = codeObj.GetValue("errorMsg");
                     if (errorToken != null)
                     {
                         string errorMsg = errorToken.Value<string>();
                         if (errorMsg.Length > 50)
                         {
                             errorMsg = errorMsg.Substring(0, 50);
                         }
                         ServerError serverError = new ServerError(code, errorMsg);
                         onHttpError(serverError);
                     }
                     else
                     {
                         Debug.Log("错误码：" + code);
                         ServerError serverError = new ServerError(code, "未知错误");
                         onHttpError(serverError);
                     }

                 }
             }
             catch (Exception e)
             {
                 Debug.Log("未知异常：" + e);
                 ServerError serverError = new ServerError(ServerError.UnknowException, e.Message);
                 onHttpError(serverError);
             }
         }, onHttpError);
    }
}
